package com.graduation.cdm.funactivity.view.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.graduation.cdm.funactivity.MyApplication;
import com.graduation.cdm.funactivity.R;
import com.graduation.cdm.funactivity.bean.ActivityBean;
import com.graduation.cdm.funactivity.bean.Page;
import com.graduation.cdm.funactivity.util.CommonAdapter;
import com.graduation.cdm.funactivity.util.DisplayUtil;
import com.graduation.cdm.funactivity.util.ownview.DepthPageTransformer;
import com.graduation.cdm.funactivity.util.progressbar.CircularProgress;
import com.graduation.cdm.funactivity.util.xUtilsImageUtils;
import com.graduation.cdm.funactivity.view.SearchActivity;
import com.graduation.cdm.funactivity.view.activityview.OperatePublishActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.graduation.cdm.funactivity.util.DateUtils.longTosmallstring;
import static com.graduation.cdm.funactivity.util.GlobalConstant.preUrl;

/**
 * Created by cdm on 2017/3/1.
 */

public class HomeFragment extends Fragment {

    private View view;
    private TextView tv_search;
    private ViewPager vp_list;
    private ScrollIndicatorView scroll_lable;
    private IndicatorViewPager indicatorViewPager;
    private int[] images = {R.mipmap.activity_fm,R.mipmap.three,R.mipmap.zz};
    Page page=new Page();
    private PullToRefreshListView ptr_arrlist_tuijian;
    private CircularProgress CircularProgress;
    CommonAdapter<ActivityBean.Activity> adapter = null;
    private int pageCount = 1;
    private int startPage = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home,container,false);

        initView();

        return view;
    }

    private void initView() {
        tv_search = ((TextView) view.findViewById(R.id.tv_search));
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("search_type", "article");
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });

        CircularProgress = ((CircularProgress) view.findViewById(R.id.progressBar_chat));
        CircularProgress.setVisibility(View.VISIBLE);

        vp_list = ((ViewPager) view.findViewById(R.id.vp_list));
        scroll_lable = (ScrollIndicatorView) view.findViewById(R.id.scroll_lable);
        vp_list.setPageTransformer(true, new DepthPageTransformer());

        float unSelectSize = 14;
        float selectSize = unSelectSize * 1.3f;
        scroll_lable.setOnTransitionListener(new OnTransitionTextListener().setColor(0xFF2196F3, Color.GRAY).setSize(selectSize, unSelectSize));

        scroll_lable.setScrollBar(new ColorBar(getActivity(), 0xFF2196F3, 4));

        indicatorViewPager = new IndicatorViewPager(scroll_lable, vp_list);
        indicatorViewPager.setAdapter(new MyAdapter());
        indicatorViewPager.setPageOffscreenLimit(0);

    }

    private class MyAdapter extends IndicatorViewPager.IndicatorViewPagerAdapter {
        private String[] labels = {"推荐","运动","技能","美食","旅行","迷幻","讲座"};
        @Override
        public int getCount() {
            return labels.length;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = View.inflate(getActivity(),R.layout.tab_top,null);
            }
            TextView textView = (TextView) convertView;
            textView.setText(labels[position]);

            int witdh = getTextWidth(textView);
            int padding = DisplayUtil.dipToPix(getActivity(), 8);
            //因为wrap的布局 字体大小变化会导致textView大小变化产生抖动，这里通过设置textView宽度就避免抖动现象
            //1.3f是根据上面字体大小变化的倍数1.3f设置
            textView.setWidth((int) (witdh * 1.3f) + padding);

            return convertView;
        }

        @Override
        public View getViewForPage(final int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = View.inflate(getActivity(),R.layout.viewpage_layout,null);
            }
            startPage = 1;
            pageCount = 1;
            final PullToRefreshListView listView = ((PullToRefreshListView) convertView.findViewById(R.id.lv));
            final List<ActivityBean.Activity> activityList = new ArrayList<>();
            adapter = new CommonAdapter<ActivityBean.Activity>(getActivity().getApplicationContext(),activityList,R.layout.tuijian_item){

                @Override
                public void convert(com.graduation.cdm.funactivity.util.ViewHolder viewHolder, ActivityBean.Activity activity, int position) {
                    TextView tv_createtime = viewHolder.getViewById(R.id.tv_createtime);
                    TextView tv_label = viewHolder.getViewById(R.id.tv_label);
                    TextView tv_theme = viewHolder.getViewById(R.id.tv_theme);
                    ImageView iv_photo = viewHolder.getViewById(R.id.iv_photo);

                    tv_createtime.setText(longTosmallstring(activity.activityBegintime));
                    tv_label.setText(activity.activityLabel);
                    tv_theme.setText(activity.activityTheme);
                    xUtilsImageUtils.displayHome(iv_photo,preUrl+activity.activityImgurl);
                }
            };

            listView.setScrollingWhileRefreshingEnabled(true);
            listView.setMode(PullToRefreshBase.Mode.BOTH);

            listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
                @Override
                public void onRefresh(PullToRefreshBase<ListView> refreshView) {

                    PullToRefreshBase.Mode mode = listView.getCurrentMode();
                    if (mode == PullToRefreshBase.Mode.PULL_FROM_START) {
                        System.out.println("PULL_FROM_START");
                        System.out.println("拉"+position+activityList+startPage);
                        getActivities(position, activityList, adapter, listView, 1);
                    } else if (mode == PullToRefreshBase.Mode.PULL_FROM_END) {
                        System.out.println("PULL_FROM_END");
                        System.out.println("拉"+position+activityList+startPage);
                        getActivities(position, activityList, adapter, listView, ++startPage);
                    }
                }
            });

            ListView newsList = listView.getRefreshableView();
            newsList.setAdapter(adapter);

            newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id){
                    // Toast.makeText(getActivity(), position, Toast.LENGTH_SHORT).show();
                    ActivityBean.Activity activityDetail = activityList.get(position - 1);
                    Intent intent = new Intent(getActivity(), OperatePublishActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("activityInfo",activityDetail);
                    //System.out.println("============"+activityList.get(position));
                    intent.putExtras(bundle);
                    startActivity(intent);

                }
            });
            System.out.println("初始"+position+activityList+startPage);
            getActivities(position, activityList, adapter, listView, startPage);

            return convertView;
        }

        @Override
        public int getItemPosition(Object object) {
            //这是ViewPager适配器的特点,有两个值 POSITION_NONE，POSITION_UNCHANGED，默认就是POSITION_UNCHANGED,
            // 表示数据没变化不用更新.notifyDataChange的时候重新调用getViewForPage
            return PagerAdapter.POSITION_UNCHANGED;
        }

        private int getTextWidth(TextView textView) {
            if (textView == null) {
                return 0;
            }
            Rect bounds = new Rect();
            String text = textView.getText().toString();
            Paint paint = textView.getPaint();
            paint.getTextBounds(text, 0, text.length(), bounds);
            int width = bounds.left + bounds.width();
            return width;
        }

    }

    private void getActivities(final int position, final List<ActivityBean.Activity> topicList, final CommonAdapter<ActivityBean.Activity> adapter, final PullToRefreshListView listView, final int page){
        String url = preUrl +"activity/getByLable";
        StringRequest stringRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                System.out.println("onResponse="+s.trim());
                CircularProgress.setVisibility(View.GONE);
                Gson gson = new Gson();
                ActivityBean activityBean = gson.fromJson(s, ActivityBean.class);
                pageCount = Integer.parseInt(activityBean.pageSum);
                if (page == 1) {
                    topicList.clear();
                }
                if (page <= pageCount) {
                    topicList.addAll(activityBean.activityList);
                }else {
                    Toast.makeText(getActivity(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
                }

                listView.onRefreshComplete();
                System.out.println(topicList);
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("onErrorResponse="+volleyError.toString());
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map=new HashMap<>();
                map.put("pageNow",page+"");
                map.put("pageSize",5+"");
                System.out.println("position=="+position);
                map.put("lablePosition",position+"");
                return map;
            }
        };
        MyApplication.getRequestQueue().add(stringRequest);
    }

}
